package com.flink.api.unit5;

import com.flink.pojo.WaterSensor;
import org.apache.flink.api.java.functions.KeySelector;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.KeyedStream;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;

/**
 * keyBy_1
 *
 * @author caizhiyang
 * @since 2024-02-21
 */
public class max_1 {

    public static void main(String[] args) throws Exception {
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        env.setParallelism(1);

        DataStreamSource<WaterSensor> source = env.fromElements(
                new WaterSensor("sensor_1", 11L, 11),
                new WaterSensor("sensor_1", 1L, 1),
                new WaterSensor("sensor_2", 2L, 2),
                new WaterSensor("sensor_3", 3L, 3),
                new WaterSensor("sensor_4", 4L, 4)
        );


        //得到的是KeyedStream。可以认为是分区流，它是对DataStream按照key的一个逻辑分区，所以泛型有两个类型：除去当前流中的元素类型外，还需要指定key的类型。
        KeyedStream<WaterSensor, String> waterSensorStringKeyedStream = source.keyBy(new KeySelector<WaterSensor, String>() {
            @Override
            public String getKey(WaterSensor waterSensor) throws Exception {
                return waterSensor.getId();
            }
        });

        // max() pojo指定字段名称
//        waterSensorStringKeyedStream.sum("vc").print();
        /**
         * 输出结果为:
         * WaterSensor{id='sensor_1', ts=11, vc=11}
         * WaterSensor{id='sensor_1', ts=11, vc=12}   //按id分组后,vc值进行累加,其他列值保持流第一条数据的值
         * WaterSensor{id='sensor_2', ts=2, vc=2}
         * WaterSensor{id='sensor_3', ts=3, vc=3}
         * WaterSensor{id='sensor_4', ts=4, vc=4}
         */

        // min() pojo指定字段名称
//        waterSensorStringKeyedStream.min("vc").print();
        /**
         * 输出结果为:
         * WaterSensor{id='sensor_1', ts=11, vc=11}
         * WaterSensor{id='sensor_1', ts=11, vc=1}     //按id分组后,保留vc最小的那一列的值,其他列值保持流第一条数据的值
         * WaterSensor{id='sensor_2', ts=2, vc=2}
         * WaterSensor{id='sensor_3', ts=3, vc=3}
         * WaterSensor{id='sensor_4', ts=4, vc=4}
         */

        // min() pojo指定字段名称
        waterSensorStringKeyedStream.minBy("vc").print();
        /**
         * 输出结果为:
         * WaterSensor{id='sensor_1', ts=11, vc=11}
         * WaterSensor{id='sensor_1', ts=1, vc=1}    //按id分组后,minBy()会返回包含字段最小值的整条数据
         * WaterSensor{id='sensor_2', ts=2, vc=2}
         * WaterSensor{id='sensor_3', ts=3, vc=3}
         * WaterSensor{id='sensor_4', ts=4, vc=4}
         */
        env.execute();
    }
}
